﻿using Microsoft.IdentityModel.Tokens;
using RestfulApiV1.Domain.Configure;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace RestfulApiV1.Utils.Auth
{
    public class TokenHelper
    {
        /// <summary>
        /// 生成AccessToken
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="rolename">角色名</param>
        /// <returns></returns>
        public static string GenerateToken(string username, string rolename,TokenParameter tokenParameter)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Name,username),
                new Claim(ClaimTypes.Role,rolename)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var securityToken = new JwtSecurityToken(tokenParameter.Issuer, null, claims, expires: DateTime.UtcNow.AddMinutes(tokenParameter.AccessExpiration), signingCredentials: credentials);

            //生成token
            var token = new JwtSecurityTokenHandler().WriteToken(securityToken);

            return token;
        }
    }
}
